/*
 * Copyright 2015 泛泛o0之辈
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.jfast.framework.jdbc.orm;

import cn.jfast.framework.base.util.ErrorCode;
import cn.jfast.framework.base.util.ClassUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.*;

/**
 * 解析SQL可使用参数
 */
public abstract class Wrapper{

    protected Type[] paramTypes;
    protected String[] paramNames;
    protected Object[] args;
    protected Map<String,Object> paramMaps = new HashMap<String, Object>();
    protected Type returnType;
    protected Connection conn;
    protected PreparedStatement ps;
    protected List<Object> sqlFields = new LinkedList<Object>();
    protected Method method;

    /**
     * 封装SQL传入参数Map
     * @return
     * @throws IllegalAccessException
     */
    public Map<String,Object> wrapParam() throws IllegalAccessException, SqlException {
        String paramName;
        Object paramValue;
        for(int i=0;i<paramNames.length;i++){
            paramName = paramNames[i];
            paramValue = args[i];
            wrapPrimitiveValue(paramName,paramValue);
        }
        return  this.paramMaps;

    }

    @SuppressWarnings("unchecked")
	private void wrapPrimitiveValue(String paramName,Object paramValue) throws IllegalAccessException, SqlException {
        if(null == paramValue) {
            paramMaps.put(paramName.toLowerCase(),null);
        } else {
            if (ClassUtils.isCommonTypeOrWrapper(paramValue.getClass())  //判断对象是否基本类型,集合或者数组
                    || paramValue instanceof Collection
                    || paramValue.getClass().isArray()) {
                if (null != paramMaps.get(paramName.toLowerCase()))
                    throw new SqlException(ErrorCode.REPEAT_PARAM);
                if (paramValue instanceof Map) {
                    @SuppressWarnings("rawtypes")
					Iterator<Map.Entry<?,?>> ite = ((Map)paramValue).entrySet().iterator();
                    while (ite.hasNext()) {
                        Map.Entry<?,?> entry = ite.next();
                        if (ClassUtils.isCommonTypeOrWrapper(entry.getValue().getClass()))
                            paramMaps.put(String.valueOf(entry.getKey()), entry.getValue());
                        else
                            throw new SqlException(ErrorCode.ERROR_PARAM_TYPE);
                    }
                } else if (paramValue instanceof Collection) {
                    paramMaps.put(paramName.toLowerCase(), ((Collection<?>) paramValue).toArray());
                } else {
                    paramMaps.put(paramName.toLowerCase(), paramValue);
                }
            } else {
                wrapMultiValue(paramValue);
            }
        }
    }

    @SuppressWarnings("unchecked")
	private void wrapMultiValue(Object paramValue) throws IllegalAccessException, SqlException {
        Field[] fields = paramValue.getClass().getDeclaredFields();
        for (Field field : fields) {
		    field.setAccessible(true);
		    Object obj = field.get(paramValue);
		    if (null == obj) {
		        paramMaps.put(field.getName().toLowerCase(), null);
		    } else {
		        if (ClassUtils.isCommonTypeOrWrapper(obj.getClass())  //
		                || obj instanceof Collection
		                || obj.getClass().isArray()) {
		            if (null != paramMaps.get(field.getName().toLowerCase()))
		                throw new SqlException(ErrorCode.REPEAT_PARAM);
		            if (obj instanceof Map) {
		                @SuppressWarnings("rawtypes")
						Iterator<Map.Entry<?,?>> ite = ((Map) obj).entrySet().iterator();
		                while (ite.hasNext()) {
		                    Map.Entry<?,?> entry = ite.next();
		                    if (ClassUtils.isCommonTypeOrWrapper(entry.getValue().getClass()))
		                        paramMaps.put(String.valueOf(entry.getKey()), entry.getValue());
		                    else
		                        throw new SqlException(ErrorCode.ERROR_PARAM_TYPE);
		                }
		            } else if (obj instanceof Collection) {
		                paramMaps.put(field.getName().toLowerCase(), ((Collection<?>) obj).toArray());
		            } else {
		                paramMaps.put(field.getName().toLowerCase(), obj);
		            }
		        } else {
		            wrapMultiValue(obj);
		        }
		    }
		}
    }

}
